package com.qingfeng.base.controller;

import com.alibaba.fastjson.JSONObject;
import com.qingfeng.base.dao.SpringSessionMapper;
import com.qingfeng.base.model.TMenuResource;
import com.qingfeng.base.service.MenuResourcService;
import com.qingfeng.base.util.CodeEnum;
import com.qingfeng.base.util.ResponseMessage;
import com.qingfeng.client.bean.Seller;
import com.qingfeng.client.bean.Store;
import com.qingfeng.client.dao.SellerMapper;
import com.qingfeng.client.dao.StoreMapper;
import com.qingfeng.util.ApiMsg;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;

/**
 * @Author:zhangyuefei
 * @Date:2019/9/6 14:39
 */
@Slf4j
@RestController
public class HomeController {

    @Autowired
    private SellerMapper tUserMapper;

    @Autowired
    private SpringSessionMapper springSessionMapper;

    @Autowired
    private MenuResourcService menuResourcService;

    @Autowired
    private StoreMapper storeMapper;

    @Value("${isConcurrent}")
    private String isConcurrent;
    @Value("${wrongCounts}")
    private int wrongCounts;


//    @RequestMapping({"/whoim","/whoim2"})
//    public Object whoim(){
//        Seller u = (Seller) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
//        return u;
//    }
//
//
//    @RequestMapping({"/","/index"})
//    public String index(){
//        Seller tUser = tUserMapper.loginUserByAccount("admin");
//        return "this is index"+tUser;
//    }

    @RequestMapping("/login_p")
    @ResponseStatus(HttpStatus.FORBIDDEN)
    public ApiMsg loginP(){
        return new ApiMsg(CodeEnum.UNAUTHORIZED.getCode(),CodeEnum.UNAUTHORIZED.getMsg(),null);
    }

    @RequestMapping("/loginError")
    public String loginError(){
        return "登录失败,loginError";
    }

    /**
     * 登录成功重定向
     * @param request
     * @return
     */
    @RequestMapping("/loginSuccessHandler")
    public ResponseMessage loginSuccessHandler(HttpServletRequest request, HttpServletResponse response){

        String username = request.getParameter("username");
        request.getSession().setAttribute("xx",username);
        log.info(username+" login success");
        //用户登录成功信息
        Seller user = (Seller) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        TMenuResource menu = menuResourcService.selectMenu();
        List<TMenuResource> resources = user.getResources();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("meu",menu);
        jsonObject.put("resuorce",resources);
        jsonObject.put("user",user);
        if (user.getStoreId()!=null) {
            Store store = storeMapper.selectById(user.getStoreId());
            jsonObject.put("store",store);
        }


        ResponseMessage responseMessage = new ResponseMessage(CodeEnum.SUCCESS.getCode(),"登录成功", jsonObject);
        //判断是否需要顶掉他人登录
        if (isConcurrent.equals("1")) {
            springSessionMapper.deleteById(username);
        }
        //登录成功清
        user.setWrongCount(0);
        user.setLastLoginTime(new Date());
        tUserMapper.updateById(user);
        return responseMessage;
    }

    @ResponseBody
    @RequestMapping("/logoutSuccess")
//    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public ResponseMessage logout() {
        return new ResponseMessage(CodeEnum.SUCCESS.getCode(),"退出成功","");
    }



//    /**
//     * 登录失败重定向
//     * @param request
//     * @return
//     */
//    @RequestMapping("/loginFailureHandler")
//    public ResponseMessage loginFailureHandler(HttpServletRequest request){
//        String username = request.getParameter("username");
//        String password = request.getParameter("password");
//        log.info(username+" login failure");
//
//        ResponseMessage responseMessage = null;
//        TUser user = tUserMapper.loginUserByAccount(username);
//        //密码输入错误次数+1
//        Integer wrongCount = user.getWrongCount();
//        wrongCount++;
//        if (wrongCount<wrongCounts){
//            responseMessage = new ResponseMessage(ResultCodeEnum.ERROR.getCode(), "密码输入错误!您还剩" + (wrongCounts - wrongCount) + "次登录机会","");
//        }
//        if (wrongCount == wrongCounts) {
//            //输入密码错误三次 冻结账号
//
//            user.setUnlockTime(new Date(System.currentTimeMillis()+(5*60000)));
//            responseMessage = new ResponseMessage(ResultCodeEnum.ERROR.getCode(), "账户被锁定，请5分钟后重试","");
//        }
//        if (wrongCount>wrongCounts){
//            int i = wrongCount - wrongCounts;
//           switch (i){
//               case 1:
//                   user.setUnlockTime(new Date(System.currentTimeMillis()+(30*60000)));
//                   responseMessage = new ResponseMessage(ResultCodeEnum.ERROR.getCode(), "账户被锁定，请30分钟后重试","");
//                   break;
//               case 2:
//                   user.setUnlockTime(new Date(System.currentTimeMillis()+(60*60000)));
//                   responseMessage = new ResponseMessage(ResultCodeEnum.ERROR.getCode(), "账户被锁定，请1小时后重试","");
//                   break;
//               case 3:
//                   user.setUnlockTime(new Date(System.currentTimeMillis()+(24*60*60000)));
//                   responseMessage = new ResponseMessage(ResultCodeEnum.ERROR.getCode(), "账户被锁定，请1天后重试","");
//                   break;
//                   default:
//                       user.setLock(0);
//                       responseMessage = new ResponseMessage(ResultCodeEnum.ERROR.getCode(), "账户被锁定，请联系管理员","");
//                       break;
//           }
//        }
//        user.setWrongCount(wrongCount);
//
//        tUserMapper.updateById(user);
//        return responseMessage;
//    }

    @RequestMapping("/test")
    public Object getUerInfo(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Seller seller = (Seller) authentication.getPrincipal();
        return seller;
    }

}
